package com.ziytek.web.citizen.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ziytek.web.citizen.config.ConfigInit;
import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.mapper.CapacitySchemeMapper;
import com.ziytek.web.citizen.model.bean.BatteryLevelData;
import com.ziytek.web.citizen.model.bean.BatteryLevelDetailsData;
import com.ziytek.web.citizen.model.bean.CapacityLevel;
import com.ziytek.web.citizen.model.req.CapacityDetailsQueryReq;
import com.ziytek.web.citizen.model.req.CapacityStatisticsQueryReq;
import com.ziytek.web.citizen.model.rsp.CapacityDetailsQueryRsp;
import com.ziytek.web.citizen.model.rsp.CapacityStatisticsQueryRsp;
import com.ziytek.web.citizen.pojo.basic.BasicCapacityScheme;
import com.ziytek.web.citizen.service.itf.CapacityDetailsServer;
import com.ziytek.web.citizen.util.CabinetNoUtil;
import com.ziytek.web.citizen.util.ChargeTypeUtil;
import com.ziytek.web.citizen.util.NumberToUtils;
import com.ziytek.web.citizen.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分容柜电池电芯分容电池容量详情数据查询接口
 *
 * @author fenghx
 * @version v1.0
 * @className DischargeCapacityDetailsServerImpl
 * @date 2023/8/7 15:03
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CapacityDetailsServerImpl implements CapacityDetailsServer {
    private final Gson gson;
    private final ConfigInit configInit;
    private final CapacitySchemeMapper capacitySchemeMapper;


    @Override
    public CapacityDetailsQueryRsp capacityDetailsQuery(CapacityDetailsQueryReq req) {
        CapacityDetailsQueryRsp response = new CapacityDetailsQueryRsp();

        if (req == null || StringUtil.isEmpty(req.getSchemeId()) || StringUtil.isEmpty(req.getCabinetNo()) || StringUtil.isEmpty(req.getLevel())) {
            response.error();
            response.setRetMsg("请求参数异常");
            return response;
        }

        String cabinetNo = CabinetNoUtil.getCabinetNo(req.getCabinetNo());
        String level = req.getLevel();
        String[] levelStr = level.split("-");
        if (levelStr.length != NumConstant.INT_TWO) {
            response.error();
            response.setRetMsg("请求参数异常");
            return response;
        }

        Float capStart = StringUtil.toFloat(levelStr[NumConstant.INT_ZERO]);
        Float capEnd = StringUtil.toFloat(levelStr[NumConstant.INT_ONE]);

        //String setType = SettingConstant.CONSTANT_CURRENT_DISCHARGE;
        List<String> setTypeList = ChargeTypeUtil.getChargeTypeList();

        if (capStart <= NumConstant.FLOAT_ZER) {
            capStart = configInit.getMinCapStatsQuery();
        }
        if (capEnd >= NumConstant.FLOAT_TEN_THOUSAND) {
            capStart = NumConstant.FLOAT_ZER;
        }

        // 右区间统计精确到.999999
        capEnd = capEnd + NumConstant.FLOAT_SMART_LT_ONE;

        //SettingsIssuedNumberTable settingsIssuedNumber = settingsIssuedNumberMapper.selectByNumber(cabinetNo, SettingConstant.SET_TYPE_DISCHARGE);
        //long settingsIssuedNumberVersion = settingsIssuedNumber != null ? settingsIssuedNumber.getNumber() : NumConstant.LONG_ZERO;

        //List<StageIssuedTable> last = stageBatchMapper.findByCabinetNoAndCapacityBetweenOrderByUpdateTimeDesc(cabinetNo, setTypeList, capStart, capEnd, settingsIssuedNumberVersion);
        // List<DischargeCapacityTable> last = dischargeCapacityMapper.findByCabinetNoAndCapacityBetweenOrderByUpdateTimeDesc(cabinetNo, setTypeList, capStart, capEnd);
        // if (CollectionUtils.isEmpty(last)) {
        //response.success();
        //return response;
        //  }

//        // 查询总数不足512个数据的补全数据
//        if (capEnd >= NumConstant.FLOAT_TEN_THOUSAND && last.size() < NumConstant.INT_FIVE_HUNDRED_TWO) {
//            //toAllStageIssuedDataProcess(last);
//            toAllStageIssuedDataProcessNew(last);
//        }


        List<BatteryLevelDetailsData> batteryLevelDetailsDats = new ArrayList<>();
//        for (DischargeCapacityTable data : last) {
//            BatteryLevelDetailsData b = new BatteryLevelDetailsData();
//            b.setNo(data.getKey());
//            b.setV(data.getVoltage());
//            b.setCap(data.getCapacity());
//            batteryLevelDetailsDats.add(b);
//        }

        // 按分控位置从小到大排序  按电芯位置从小到大排序
        batteryLevelDetailsDats = batteryLevelDetailsDats.stream()
                .sorted(Comparator.comparing(a -> StringUtil.stringToInt(a.getNo(), NumConstant.INT_THREE)))
                .collect(Collectors.toList());
        response.setData(batteryLevelDetailsDats);

        response.success();
        return response;
    }

    @Override
    public CapacityStatisticsQueryRsp capacityDetailsStats(CapacityStatisticsQueryReq req) {
        CapacityStatisticsQueryRsp response = new CapacityStatisticsQueryRsp();
        if (req == null || StringUtil.isEmpty(req.getSchemeId()) || StringUtil.isEmpty(req.getCabinetNo())) {
            response.error();
            response.setRetMsg("请求参数异常");
            return response;
        }

        BasicCapacityScheme scheme = capacitySchemeMapper.findFirstById(StringUtil.toLong(req.getSchemeId()));
        if (scheme == null) {
            response.error();
            response.setRetMsg(String.format("分容方案[%s]不存在", req.getSchemeId()));
            return response;
        }

        List<CapacityLevel> capacityLevels = (gson.fromJson(scheme.getSchemes(), new TypeToken<List<CapacityLevel>>() {
        }.getType()));
        if (CollectionUtils.isEmpty(capacityLevels)) {
            response.error();
            response.setRetMsg(String.format("分容方案[%s]分容等级设置错误", req.getSchemeId()));
            return response;
        }

        // 排序
        capacityLevels.sort(Comparator.comparing(CapacityLevel::getLevelStart));

        List<BatteryLevelData> data = new ArrayList<>();
        String cabinetNo = CabinetNoUtil.getCabinetNo(req.getCabinetNo());

        //SettingsIssuedNumberTable settingsIssuedNumber = settingsIssuedNumberMapper.selectByNumber(cabinetNo, SettingConstant.SET_TYPE_DISCHARGE);
        //long settingsIssuedNumberVersion = settingsIssuedNumber != null ? settingsIssuedNumber.getNumber() : NumConstant.LONG_ZERO;

//        String setType = SettingConstant.CONSTANT_CURRENT_DISCHARGE;
        List<String> setTypeList = ChargeTypeUtil.getChargeTypeList();
        //long total = stageBatchMapper.findStatsByCabinetNoCount(cabinetNo, setTypeList, configInit.getMinCapStatsQuery(), NumConstant.FLOAT_TWENTY_THOUSAND, settingsIssuedNumberVersion);
        // long total = dischargeCapacityMapper.findStatsByCabinetNoCount(cabinetNo, setTypeList, configInit.getMinCapStatsQuery(), NumConstant.FLOAT_TWENTY_THOUSAND);
        long total = 0L;
        float totalFloat = StringUtil.toFloat(String.valueOf(total));
        if (total > NumConstant.LONG_ZERO) {
            for (CapacityLevel cl : capacityLevels) {
                Float capStart = StringUtil.toFloat(String.valueOf(cl.getLevelStart()));
                if (capStart <= NumConstant.FLOAT_ZER) {
                    capStart = configInit.getMinCapStatsQuery();
                }
                float capEnd = StringUtil.toFloat(String.valueOf(cl.getLevelEnd()));
                // 右区间统计精确到.999999
                capEnd = capEnd + NumConstant.FLOAT_SMART_LT_ONE;
                //long count = stageBatchMapper.findStatsByCabinetNoCount(cabinetNo, setTypeList, capStart, capEnd, settingsIssuedNumberVersion);
                //long count = dischargeCapacityMapper.findStatsByCabinetNoCount(cabinetNo, setTypeList, capStart, capEnd);
                long count = 0L;
                BatteryLevelData d = new BatteryLevelData();
                d.setLevel(cl.getLevelStart() + "-" + cl.getLevelEnd());
                d.setTotal(String.valueOf(count));
                Float countFloat = StringUtil.toFloat(String.valueOf(count));
                d.setPercentage(String.valueOf(NumberToUtils.getDecimalPoint((countFloat * NumConstant.FLOAT_HUNDRED) / totalFloat, NumConstant.INT_TWO)));
                data.add(d);
            }
        }

        response.setData(data);
        response.success();
        return response;
    }
//
//    private void toAllStageIssuedDataProcessNew(List<DischargeCapacityTable> dischargeCapacityList) {
//        if (CollectionUtils.isEmpty(dischargeCapacityList)) {
//            log.info("查询分容详情数据为空");
//            return;
//        }
//
//        // 数据不足512，补全数据
//        if (dischargeCapacityList.size() < NumConstant.INT_FIVE_HUNDRED_TWO) {
//            String cabinetNo = dischargeCapacityList.getFirst().getCabinetNo();
//            log.info("cabinetNo[{}]分容详情数据不足512，补全数据 ", cabinetNo);
//
//            List<String> keyList = positionCacheConfig.getValueListByCabinetNo(cabinetNo);
//            if (CollectionUtils.isEmpty(keyList)) {
//                return;
//            }
//
//            List<String> keyStr = dischargeCapacityList.stream().map(DischargeCapacityTable::getKey).toList();
//            List<String> instAllKey = keyList.stream().filter(t -> !keyStr.contains(t)).toList();
//
//            if (!CollectionUtils.isEmpty(instAllKey)) {
//                instAllKey.forEach(k -> {
//                    DischargeCapacityTable i = new DischargeCapacityTable();
//                    i.setKey(k);
//                    i.setCapacity(NumConstant.FLOAT_ZER);
//                    i.setCurrent(NumConstant.FLOAT_ZER);
//                    i.setVoltage(NumConstant.FLOAT_ZER);
//                    dischargeCapacityList.add(i);
//                });
//            }
//        }
//    }
}
